package com.zha;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.HColumnDescriptor;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Random;

public class Zuoye2_1 {
    public static Connection conn = null;
    public static TableName tName = TableName.valueOf("t_course");
    public static Random ra = new Random();//找一个随机数
    @Before
    public void init() throws IOException{
        Configuration conf = HBaseConfiguration.create();
        conf.set("hbase.zookeeper.quorum", "hbase:2181,hbase-01:2181,hbase-02:2181");
        conn = ConnectionFactory.createConnection(conf);
}

    /**
     * 创建课程表
     * @throws IOException
     */
    @Test
    public void create() throws IOException{
        Admin admin = conn.getAdmin();
        if(admin.tableExists(tName)){
            admin.disableTable(tName);
            admin.deleteTable(tName);
        }
        HTableDescriptor ht = new HTableDescriptor(tName);
        //创建列族定义描述对象
        HColumnDescriptor hc = new HColumnDescriptor("cf1".getBytes());
        //设置该列族中存储数据的最大版本数，默认是1
        hc.setMaxVersions(5);
        hc.setBlockCacheEnabled(true);
        hc.setBlocksize(180000);
        //将列族定义信息对象放入表定义对象中
        ht.addFamily(hc);
        //用DDL操作器对象：admin来建表
        admin.createTable(ht);
        System.out.println("表创建完成");
    }

    /**
     * 课程表插入数据
     * @throws IOException
     */
    @Test
    public void insert() throws IOException{
        Table table = conn.getTable(tName);
        ArrayList<Put> putList = new ArrayList<Put>();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-ddHH:mm:ss");
        for (int i=1; i<10;i++){
            String id = format.format(new Date());
            id = id.replace("-","").replace(":","");
            id = "course" + getRowKey(id);
            Put put = new Put(id.getBytes());
            String name = "Course"+ i;
            put.addColumn("cf1".getBytes(), "name".getBytes(), name.getBytes());
            putList.add(put);
        }
        table.put(putList);
        System.out.println("数据插入完成");
    }
    @After
    public void after() throws IOException{
        if (conn!=null){
            conn.close();
        }
    }
    private String getRowKey(String id){
        return id +""+ra.nextInt(99999);
    }
}
